package org.github.project.strategy;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 文件解析服务
 *
 * @auther yang
 * @date 2022/1/21 12:35
 */
@Service
public class FileResolveService implements ApplicationContextAware {

    private Map<FileTypeEnum, IFileResolveStrategy> resolveStrategyMap = new ConcurrentHashMap<>();

    // 解析文件调用这个方法即可
    public void resolve(FileTypeEnum type, Object param) {
        IFileResolveStrategy strategy = resolveStrategyMap.get(type);
        assert strategy != null;
        strategy.resolve(param);
    }

    // 初始化 resolveStrategyMap
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        applicationContext.getBeanProvider(IFileResolveStrategy.class)
                .stream().forEach(strategy -> this.resolveStrategyMap.put(strategy.getFileType(), strategy));
    }


    // resolve HTML
    @Component
    public static class HtmlResolveStrategy implements IFileResolveStrategy {
        @Override
        public FileTypeEnum getFileType() {
            return FileTypeEnum.HTML;
        }

        @Override
        public void resolve(Object param) {
            System.out.println("解析 HTML 文件");
        }
    }

    // resolve TXT
    @Component
    public static class TxtResolveStrategy implements IFileResolveStrategy {
        @Override
        public FileTypeEnum getFileType() {
            return FileTypeEnum.TXT;
        }

        @Override
        public void resolve(Object param) {
            System.out.println("解析 TXT 文件");
        }
    }

    // resolve XML
    @Component
    public static class XmlResolveStrategy implements IFileResolveStrategy {
        @Override
        public FileTypeEnum getFileType() {
            return FileTypeEnum.XML;
        }

        @Override
        public void resolve(Object param) {
            System.out.println("解析 XML 文件");
        }
    }
}
